package com.epam.tags;

import java.io.IOException;
import java.util.List;

import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.log4j.Logger;

import com.epam.entity.AbstractEntity;

public class PaginationTagHandler extends TagSupport {
	
	private static Logger LOG = Logger.getLogger(PaginationTagHandler.class);
	private static final long serialVersionUID = 1L;
	
	private String address;
	private String command;
	private List<AbstractEntity> entityList;
	
	public int doStartTag() {
		
		JspWriter out = pageContext.getOut();
		
		try {
	//	out.println("<c:if test='${requestScope.entityList ne null}'>");
		
		if (command.equals("loadAllUsers")) {
			out.println("<table><tr><th>ID</th><th>Login</th><th>Role</th></tr>");
		} else {
		out.println("<table><tr><th>Country</th><th>Duration</th><th>Type</th><th>Transport</th><th>Hotel</th><th>Cost</th><th>Last Minute</th></tr>");
		}
		out.println("<c:forEach items='${entityList}' var='entity'>");
		if (command.equals("loadAllUsers")) {
		out.println("<t:user user='${entity}'/><p>");	
		System.out.println("HERE");
		} else {
		out.println("<t:tour voucher='${entity}'/><p>");
		}
		out.println("</c:forEach></table>");
		
		
		out.println("<table border='1' cellpadding='5' cellspacing='5'>");
		out.println("<tr><c:forEach begin='1' end='${requestScope.numberOfPages}' var='i'>");
        out.println("<c:choose> <c:when test='${requestScope.pageNumber eq i}'>");  
        out.println("<td>${i}</td> </c:when>");
        out.println("<c:otherwise><td><a href='controller?action=" + command + "&pageNumber=${i}&address=" + address + "'>${i}</a></td>");         
        out.println("</c:otherwise></c:choose></c:forEach></tr></table>");               
                   
        out.println("<c:if test='${requestScope.pageNumber ne 1}'>");         
        out.println("<a href='controller?action=" + command + "&pageNumber=${requestScope.pageNumber - 1}&address=" + address + "'> Previous </a>");                
        out.println("</c:if>");            
                
        out.println("<c:if test = '${requestScope.pageNumber lt requestScope.numberOfPages}'>");
        out.println("<a href='controller?action=" + command + "&pageNumber=${requestScope.pageNumber + 1}&address='" + address + "'> Next </a>");
        out.println("</c:if>");
        
		} catch (IOException e) {
			LOG.error(e);
		}
		
		return SKIP_BODY;
	}
	
	
	
	
	
	
	
	
	
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getCommand() {
		return command;
	}
	public void setCommand(String command) {
		this.command = command;
	}

	public List<AbstractEntity> getEntityList() {
		return entityList;
	}

	public void setEntityList(List<AbstractEntity> entityList) {
		this.entityList = entityList;
	}
	
	
	
	
}
